<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\facade\Cache;
use app\api\model\Order;
use think\Request;
use wechat\Wechat;
use think\Db;

class User extends Api
{
    //用户注册
    public function add()
    {
        if($this->request->isPost())
        {
            $post = input('post.');
            if($post){
                $post = array_filter($post);
                if(empty($post)){
                    return fh(1,'error','空数据',[]);
                }
                if(!isset($post['username']) || !isset($post['password'])){
                    return fh(1,'error','缺少账号密码',$post);
                }
            	Db::startTrans();
                try{
                	$user = model('user')->where('username','=',$post['username'])->find();
	                if($user){
	                    return fh(404,'error','该账号已存在',[]);
	                }
	                if(isset($post['parent_id'])){
	                	$post['$post'] = $post['parent_id'];
	                }
	                $post['status'] = 20;
	                $post['identitynameid'] = 10;
	                $post['identity'] = '普通用户';
	                $post['relation'] = 3;
	                $post['password'] = jm($post['password']);
	                $post['images'] = '/images/mr.png';
                    model('user')->save($post);
                    $id = model('user')->id;
                    //生成微信二维码
                    $token = $this->token();
                    $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
                    
                    $p = [
                    	'page' => 'pages/login/index',
                    	"scene" => $id
                    ];
                    $data = json_encode($p);
                    $res = curl_send([
                        'url'=>$url,
                        'method'=>'post',
                        'data'=>$data
                    ]);
                    //通过返回的参数保存在本地；
                    file_put_contents('code/'."wx".$id.".png", $res['content']);
                    model('user')->save(['ewmimages'=>'/code/'."wx".$id.".png"],['id'=>$id]);
                    Db::commit();
                }catch (\Exception $e){
                    Db::rollback();
                    return fh(500,'error',$e->getMessage(),[]);
                }
                return fh(200,'success','注册成功',[]);
            }else{
                return fh(1,'error','没有post数据',[]);
            }
        }else{
	    	$post = input('get.');
	            if($post){
	                $post = array_filter($post);
	                if(empty($post)){
	                    return fh(1,'error','空数据',[]);
	                }
	                if(!isset($post['username']) || !isset($post['password'])){
	                    return fh(1,'error','缺少账号密码',$post);
	                }
	            	Db::startTrans();
	                try{
	                	$user = model('user')->where('username','=',$post['username'])->find();
		                if($user){
		                    return fh(1,'error','该账号已存在',[]);
		                }
		                if(isset($post['parent_id'])){
	                		$post['$post'] = $post['parent_id'];
	                	}
		                $post['status'] = 20;
		                $post['identitynameid'] = 10;
		                $post['identity'] = '普通用户';
		                $post['relation'] = 3;
		                $post['password'] = jm($post['password']);
		                $post['images'] = '/images/mr.png';
	                    model('user')->save($post);
	                    $id = model('user')->id;
	                    //生成微信二维码
	                    $token = $this->token();
	                    $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
	                    $data = "{\""."scene\"".":"."\"pages/login/index?id=" . $id ."\"}";
	                    $res = curl_send([
	                        'url'=>$url,
	                        'method'=>'post',
	                        'data'=>$data
	                    ]);
	                    //通过返回的参数保存在本地；
	                    file_put_contents('code/'."wx".$id.".png", $res['content']);
	                    model('user')->save(['ewmimages'=>'/code/'."wx".$id.".png"],['id'=>$id]);
	                    Db::commit();
	                }catch (\Exception $e){
	                    Db::rollback();
	                    return fh(500,'error',$e->getMessage(),[]);
	                }
	                return fh(200,'success','注册成功',[]);
	            }else{
	                return fh(1,'error','没有post数据',[]);
	            }
        }
    }
    //修改图片
    public function img()
    {
    	if($this->request->isPost())
    	{
    		$post = input('post.');
    		if(!isset($post['id'])){
    			return fh(1,'error','缺少用户id',[]);
    		}
    		$id = $post['id'];
	    	$file = request()->file('file');
	    	// 移动到框架应用根目录/public/uploads/ 目录下
	    	if($file){
	        	$info = $file->move('upload/tx/');
		        if($info){
		            // 成功上传后 获取上传信息
		            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
		            $img = $info->getSaveName();
		        }else{
		            // 上传失败获取错误信息
		            echo $file->getError();
		    		}
			}else{
				$file = '失败';
			}
			model('user')->save(['images'=>'/upload/tx/'.$img],['id'=>$id]);
			$user = model('user')->get($id)->toArray();
    	}else{
    		return fh(3,'error','不是post请求',[]);
    	}
    	return fh(200,'success','修改成功',$user);
    }
    //推荐注册
    public function useradd()
    {
        if($this->request->isGet())
        {
            $get = input('get.');
            $id = $get['user_id'] ?? '0';
            if($id){
                $user = model('user')->where('id','=',$get['user_id'])->find()->toArray();
            }else{
                //没有推荐人,用公共推荐
                return fh(404,'error','没有推荐人',[]);
            }
            //推荐人身份
            $sf = array_filter(explode(',',$user['identity']));
            foreach ($sf as $v){
                if($v == '普通用户'){
                    return fh(1,'error','该用户身份不够',[]);
                }
            }
        }
        if($this->request->isPost())
        {
            $post = input('post.');
            $post['status'] = 20;
            $post['identitynameid'] = 10;
            $post['identity'] = '普通用户';
            $post['parent_id'] = input('user_id');
            $post['relation'] = 1;
            $post['password'] = jm($post['password']);
            model('user')->save($post);
            $id = model('user')->id;
            ewm($id);
        }
        return $this->fetch();
    }
    //用户数据修改
    public function updete()
    {
        if($this->request->isPost())
        {
        	
            $post = input('post.');
            $posts = array_filter($post);
            if(!isset($post['id'])){
                return fh(404,'error','缺少用户ID',[$post,$posts]);
            }
            $id = $post['id'];
            $post['id'] = '';
            $post = array_filter($post);
            Db::startTrans();
            try{
            $post['images'] = $post['images'] ?? false;
            if($post['images']){
                $hz = explode('.',$post['images']);
                $hz = array_pop($hz);
                $img = $post['images'];
                //$address = $_SERVER['DOCUMENT_ROOT']."/upload/tx/" .date('YmdHis') . '.' . $hz;
                if(is_dir("upload/tx/")){
                	$p = 1;
                	$aaa = move_uploaded_file($post['images'],"upload/tx/123.png");
                }else{
                	$p = 2;
                	$aaa= 555;
                }
                if(!$aaa){
            		return fh(1,'error','编辑失败',[$aaa,$img]);
                }
                $post['images'] = "upload/tx/123.png";
            }else{
            	$hz = 0;
            	$address = 0;
            }
            $post = array_filter($post);
            $model = model('user')->save($post,['id'=>$id]);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return fh(500,'error',$e->getMessage(),[]);
            }
            $user = model('user')->where('id','=',$id)->find()->toArray();
            return fh(200,'success','修改成功',$user);
        }
    }
    //购买合伙人身份
    public function hhsf()
    {
        if($this->request->isPost())
        {
            $post = input('post.');
            if(!isset($post['user_id'])){
                return fh(1,'error','缺少用户id',[]);
            }
            Db::startTrans();
            try{
                $model = model('user')->save(['hhren'=>1],['id'=>$post['user_id']]);
                $user = model('user')->where('id','=',$post['user_id'])->find()->toArray();
                    Db::commit();
            }catch (\Exception $e){
                    Db::rollback();
                return fh(500,'error',$e->getMessage(),[]);
            }
            return fh(200,'success','兑换成功',$user);
        }
    }
    //我的团队人数
    public function td()
    {
        if($this->request->isPost()){
            $post = input('post.');
            if(!isset($post['user_id'])){
                return fh(1,'error','缺少用户id',[]);
            }
            Db::startTrans();
            try{
                //普通用户数量
                $user['ptyh'] = model('user')->tj($post['user_id'],10,'ptsf');
                //普通会员数量
                $user['pthy'] = model('user')->tj($post['user_id'],1,'ptsf');
                //普通代理商数量
                $user['ptdl'] = model('user')->tj($post['user_id'],3,'ptsf');
                //区代理商数量
                $user['cpqdl'] = model('user')->tj($post['user_id'],4,'canpinsf');
                //市代理商数量
                $user['cpsdl'] = model('user')->tj($post['user_id'],5,'canpinsf');
                //省代理商数量
                $user['cpshdl'] = model('user')->tj($post['user_id'],7,'canpinsf');
                //租赁人数量
                $user['zl'] = model('user')->tj($post['user_id'],1,'zls');
                //商家数量
                $user['sj'] = model('user')->tj($post['user_id'],0,'business_id','>');
                //服务中心数量
                $user['fw'] = model('user')->tj($post['user_id'],0,'fwgl_id','>');
                //管理中心数量
                $user['gl'] = model('user')->tj($post['user_id'],0,'glzx_id','>');
                //管理中心数量
                $user['all'] = $user['ptyh'] + $user['pthy'] +  $user['ptdl'] + $user['cpqdl'] + $user['cpsdl'] + $user['cpshdl'] + $user['zl'] + $user['sj'] + $user['fw'] + $user['gl'];
                    Db::commit();
            }catch (\Exception $e){
                    Db::rollback();
                return fh(500,'error',$e->getMessage(),[]);
            }
            return fh(200,'success','请求成功',$user);
        }
    }
    //登录
    public function login()
    {
        if($this->request->isPost())
        {
            $post = input('post.');
            $post = array_filter($post);
            if(!isset($post['username']) || !isset($post['password'])){
                return fh(1,'error','缺少参数',[]);
            }
            $post['password'] = jm($post['password']);
            $user = model('user')->where([['username','=',$post['username']],['password','=',$post['password']]])->find();
            if($user){
                $user = $user->toArray();
                if($user['status'] == 20){
                	return fh(1,'error','审核中',[]);
                }elseif($user['status'] == 77){
                	return fh(1,'error','该账号未通过审核',[]);
                }elseif($user['status'] == 90){
                	return fh(1,'error','该账号已被查封',[]);
                }else{
                	if($user['parent_id'] == 0){
                		if(isset($post['parent_id'])){
                			model('user')->save(['parent_id'=>$post['parent_id']],['id'=>$user['id']]);
                		}
                	}
                	return fh(200,'success','登录成功',$user);
                }
            }else{
                return fh(1,'error','账号或密码错误',[]);
            }
        }
    }
    //购买承租人
    public function gmczr()
    {
    	if($this->request->isPost())
    	{
    		$post = input('post.');
    		$code = $post['code'] ?? false;
            $post = array_filter($post);
            if(!isset($post['user_id']))
            {
                return fh(1,'error','参数缺失',$post);
            }
            if($code){
				$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$this->appid&secret=$this->appsecret&js_code=$code&grant_type=authorization_code";
				$curl = curl_send(['url'=>$url]);
				if(strpos($curl['content'],'errcode')){
					return fh(200,'error','获取openid失败'.$curl['content'],[]);
				}
				if(strpos($curl['content'],'error')){
					return fh(200,'error','获取openid失败'.$curl['content'],[]);
				}
				$arr = json_decode($curl['content']);
				// unset($arr['session_key']);
				$openid = explode(':',str_replace('}','',str_replace('"','',explode(',',$curl['content'])[1])))[1];
    		}else{
    			return fh('404','error','缺少code',[]);
    		}
            // $order = model('order')->where('id','=',$post['id'])->with('product')->find()->toArray();
            $orderid = date('YmdHis') . rand(10000,99999);
            model('order')->save(['user_id'=>$post['user_id'],'name'=>'购买承租人','content'=>'购买承租人','status'=>10,'orderid'=>$orderid]);
            $pay = $this->cecz(['name'=>'购买承租人','content'=>'购买承租人','status'=>10,'orderid'=>$orderid],$openid);
    		// return fh('404','error',json_encode($pay, JSON_UNESCAPED_UNICODE),[]);
            return json_encode($pay,JSON_UNESCAPED_UNICODE);
    		
    	}else{
            return fh('404','error','没有post数据',[]);
    	}
    }
    public function cecz($order,$openid)
    {
        $wechat = Wechat::instance($this->appid,$this->appsecret);
        $wepay = $wechat->pay($this->mchid,$this->mchkey);
        $params = [
            'body'=>$order['name'],
            'detail'=>$order['content']?: '没有介绍',
            'out_trade_no'=>$order['orderid'],
            'total_fee'=>1000*100,
            // 'total_fee'=>2,
            'notify_url'=>url('api/user/notifyfwzx', [], '', true),
            'openid'=>$openid
        ];
        $result = $wepay->unifiedorder($params);
        if($result){
            return  json_decode(fh(200,'success','请求成功',$result));
        }else{
        	// return $wepay->getErrCode .':' .$wepay->getErrMsg();
            return fh(1,'error','失败',$wepay->getErrCode .':' .$wepay->getErrMsg());
        }
    }
    public function notifyfwzx()
    {
        $xml = file_get_contents("php://input");
        trace($xml);
        header("Content-Type: application/xml;");
        //var_dump($this->appsecret);
        $wechat = Wechat::instance($this->appid,$this->appsecret);
        $payModel = $wechat->pay($this->mchid,$this->mchkey);
        //签名验证并返回订单信息
        $wxOrder = $payModel->notify();
        if (!empty($wxOrder)) {
            if (strtolower($wxOrder['return_code']) == 'success') {
                //取得系统订单
                $order = Order::getByOrderid($wxOrder['out_trade_no']);
                if (empty($order)) {
                    trace("订单未找到，订单号：{$wxOrder['out_trade_no']}\n" . var_export($wxOrder, true), 'wechat');
                } else {
                	//购买承租人
                	$id = $order['user_id'];
                	//购买的用户
                	$user = model('user')->where('id','=',$id)->find()->toArray();
                	if($user['parent_id'] > 0){
                		//上级用户id
                		$puser = model('user')->where('id','=',$user['parent_id'])->find()->toArray();
                		//上级用户拥有承租人身份的所有下级
                		$all = model('user')->where([
                			['parent_id','=',$puser['id']],
                			['zls','=',1]
                			])->select()->toArray();
                		$all = count($all);
                		if($all >= 10){
                			$iszls = 1;
                			model('user')->save(['zls'=>1,'is_zls'=>1],['id'=>$order['user_id']]);
                		}
                	}
                	model('order')->save(['status'=>40],['id'=>$order['id']]);
                	if(!isset($iszls))
                	{
                		model('user')->save(['zls'=>1],['id'=>$order['user_id']]);
                	}
                	$num = 10000;
					model('integral')->save(['source'=>17,'user_id'=>$id,'status'=>1,'num'=>$num]);
					$integralid = model('integral')->id;
					//代理商、承租人、服务中心的权益积分，均会被分为：（60%股票）（20%兑换产品）（6%税收）（14%无息贷款额度）
					$all = [];
					$all[] = ['integral_id'=>$integralid,'user_id'=>$id,'status'=>7,'num'=>$num*0.6,'class'=>1];
					$all[] = ['integral_id'=>$integralid,'user_id'=>$id,'status'=>1,'num'=>$num*0.2,'class'=>1];
					$all[] = ['integral_id'=>$integralid,'user_id'=>$id,'status'=>6,'num'=>$num*0.06,'class'=>1];
					$all[] = ['integral_id'=>$integralid,'user_id'=>$id,'status'=>3,'num'=>$num*0.14,'class'=>1];
					model('integraldetailed')->saveAll($all);
                }
            }
        }
        echo $payModel->notifyResult();
    }
    
    
    //购买商品
    public function code(){
    	if($this->request->isPost())
    	{
    		$post = input('post.');
    		$code = $post['code'] ?? false;
            $post = array_filter($post);
            if(!isset($post['id']) || !isset($post['user_id']))
            {
                return fh(1,'error','参数缺失',[]);
            }
            if($code){
				$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$this->appid&secret=$this->appsecret&js_code=$code&grant_type=authorization_code";
				$curl = curl_send(['url'=>$url]);
				$arr = json_decode($curl['content']);
				// unset($arr['session_key']);
				$openid = explode(':',str_replace('}','',str_replace('"','',explode(',',$curl['content'])[1])))[1];
    		}else{
    			return fh('404','error','缺少code',[]);
    		}
            $order = model('order')->where('id','=',$post['id'])->with('product')->find()->toArray();
            $pay = $this->ce($order,$openid);
    		// return fh('404','error',json_encode($pay, JSON_UNESCAPED_UNICODE),[]);
            return json_encode($pay);
    	}else{
            return fh('404','error','没有post数据',[]);
    	}
    }
    public function ce($order,$openid)
    {
        $wechat = Wechat::instance($this->appid,$this->appsecret);
        $wepay = $wechat->pay($this->mchid,$this->mchkey);
        $params = [
            'body'=>$order['product']['name'],
            'detail'=>$order['product']['content']?: '没有介绍',
            'out_trade_no'=>$order['orderid'],
            'total_fee'=>$order['product']['price']*$order['num']*100 ?: 1,
            // 'total_fee'=>2,
            'notify_url'=>url('api/user/notify', [], '', true),
            'openid'=>$openid
        ];
        $result = $wepay->unifiedorder($params);
        if($result){
            return  json_decode(fh(200,'success','请求成功',$result));
        }else{
        	// return $wepay->getErrCode .':' .$wepay->getErrMsg();
            return fh(1,'error','失败',$wepay->getErrCode .':' .$wepay->getErrMsg());
        }
    }
    //获取微信小程序后台AccessToken
    public function token()
    {
        if(!Cache::get('token') || (!Cache::get('time') || Cache::get('time') < time())){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
            $curl = curl_send(['url'=>$url]);
            $token = json_decode($curl['content'])->access_token;
            Cache::set('token',$token);
            Cache::set('time',time()+7200);
        }else{
            $token = Cache::get('token');
        }
        return $token;
    }
    //获取小程序码
    public function unlimited()
    {
        if($this->request->isPost())
        {
            $post = input('post.');
            $post = array_filter($post);
            if(!isset($post['id'])){
                return fh(1,'error','缺少用户ID',$post);
            }
            $token = $this->token();
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
            $data = "{\""."scene\"".":"."\"pages/login/index?id=".$post['id'] ."\"}";
            $res = curl_send([
                'url'=>$url,
                'method'=>'post',
                'data'=>$data
            ]);
            //通过返回的参数保存在本地；
            file_put_contents('code/'."wx".$post['id'].".png", $res['content']);
            model('user')->save(['ewmimages'=>'/code/'."wx".$post['id'].".png"],['id'=>$post['id']]);
        }
    }
    /**
     * 微信支付回调接口
     */
    public function notify()
    {
        $xml = file_get_contents("php://input");
        trace($xml);
        header("Content-Type: application/xml;");
        //var_dump($this->appsecret);
        $wechat = Wechat::instance($this->appid,$this->appsecret);
        $payModel = $wechat->pay($this->mchid,$this->mchkey);
        //签名验证并返回订单信息
        $wxOrder = $payModel->notify();
        if (!empty($wxOrder)) {
            if (strtolower($wxOrder['return_code']) == 'success') {
                //取得系统订单
                $order = Order::getByOrderid($wxOrder['out_trade_no']);
                if (empty($order)) {
                    trace("订单未找到，订单号：{$wxOrder['out_trade_no']}\n" . var_export($wxOrder, true), 'wechat');
                } else {
					$post['id'] = $order['id'];
					$post['user_id'] = $order['user_id'];
                    Db::startTrans();
			        try{
			            $order = model('order')->where('id','=',$post['id'])->with('product')->find()->toArray();
			            //库存减少
			            //库存
			            $num = $order['product']['stock']*1 - $order['num']*1;
			            if($num < 0){
			                return fh(404,'error','库存不足',[]);
			            }
			            //销售
			            $xsnum = $order['product']['sell']*1 + $order['num']*1;
			            model('product')->save(['sell'=>$xsnum,'stock'=>$num],['id'=>$order['product']['id']]);
			            if($order['status'] != 10){
			            	return fh(404,'error','该订单不能进行付款' . $order['status'],[]);
			            }
			            //购物用户
			            $user = model('user')->where('id','=',$post['user_id'])->find()->toArray();
			            //直属上级
			            if($user['parent_id'] == 0){
			                $pasmen = '';
			            }else{
			                $pasmen = model('user')->where('id','=',$user['parent_id'])->find();
			                if($pasmen){
			                    $pasmen = $pasmen->toArray();
			                }else{
			                    $pasmen = '';
			                }
			            }
			            //订单数据
			            $money = $order['product']['price'] * $order['num'];
			            $money = round($money,2);
			            //订单 待付款 转 待发货
			            model('order')->save(['status'=>20,'money'=>$money],['id'=>$post['id']]);
			            //添加操作记录
			            model('record')->save(['user_id'=>$post['user_id'],'title'=>'用户付款','order_id'=>$post['id']]);
			            //资产表数据增加
			            if($user['relation'] == 1){
			                model('assets')->save(['user_id'=>$post['user_id'],'class'=>3,'relation'=>1,'money'=>$money]);
			            }elseif($user['relation'] == 2){
			                model('assets')->save(['user_id'=>$post['user_id'],'class'=>3,'relation'=>2,'money'=>$money]);
			            }elseif($user['relation'] == 3){
			                model('assets')->save(['user_id'=>$post['user_id'],'class'=>3,'relation'=>3,'money'=>$money]);
			            }elseif($user['relation'] == 4){
			                model('assets')->save(['user_id'=>$post['user_id'],'class'=>3,'relation'=>2,'money'=>$money]);
			            }
			            //日对账表数据添加、修改
			            $day = model('daily')->where('time','=',date('Y-m-d'))->find();
			            if($day){
			                $day = $day->toArray();
			                //日收入
			                $daysr = $day['sr']*1 + $money*1;
			                //日收益
			                $daysy = $day['revenue']*1 + $money*1;
			                //日结算
			                $dayjs = $day['settlement']*1 + $money*1;
			                model('daily')->save(['sr'=>$daysr,'revenue'=>$daysy,'settlement'=>$dayjs],['id'=>$day['id']]);
			            }else{
			                $zuih = model('daily')->order('id','desc')->find();
			                if($zuih){
			                    $zuih = $zuih->toArray();
			                    //日收入
			                    $daysr = $day['sr']*1 + $money*1;
			                    //日收益
			                    $daysy = $day['revenue']*1 + $money*1;
			                    //日结算
			                    $dayjs = $day['settlement']*1 + $money*1;
			                    model('daily')->save(['time'=>date('Y-m-d'),'sr'=>$money,'revenue'=>$dayjs,'settlement'=>$dayjs]);
			                }else{
			                    model('daily')->save(['time'=>date('Y-m-d'),'sr'=>$money,'revenue'=>$money,'settlement'=>$money]);
			                }
			            }
			            //月对账表数据添加、修改
			            $yue = model('month')->where('time','=',date('Y-m'))->find();
			            if($yue){
			                $yue = $yue->toArray();
			                //月收入
			                $daysr = $yue['sr']*1 + $money*1;
			                //月收益
			                $daysy = $yue['revenue']*1 + $money*1;
			                //月结算
			                $dayjs = $yue['settlement']*1 + $money*1;
			                model('month')->save(['sr'=>$daysr,'revenue'=>$daysy,'settlement'=>$dayjs],['id'=>$yue['id']]);
			            }else{
			                $zuih = model('month')->order('id','desc')->find();
			                if($zuih){
			                    $zuih = $zuih->toArray();
			                    //月收入
			                    $daysr = $zuih['sr']*1 + $money*1;
			                    //月收益
			                    $daysy = $zuih['revenue']*1 + $money*1;
			                    //月结算
			                    $dayjs = $zuih['settlement']*1 + $money*1;
			                    model('month')->save(['time'=>date('Y-m'),'sr'=>$daysr,'revenue'=>$dayjs,'settlement'=>$dayjs]);
			                }else{
			                    model('month')->save(['time'=>date('Y-m'),'sr'=>$money,'revenue'=>$money,'settlement'=>$money]);
			                }
			            }
			            //进行产品购买的返现
			            if($pasmen){
			                if($pasmen['ptsf'] !== 10 && $pasmen['ptsf'] !== 3){
			                    //上级不是普通用户和普通产品代理可以得到返现30元
			                    $pasmoney = model('wallet')->where('user_id','=',$pasmen['id'])->select();
			                    if($pasmoney){
			                        $pasmoney = $pasmoney->toArray();
			                    }
			                    $money = 0;
			                    if($pasmoney){
			                        foreach ($pasmoney as $v){
			                            if($v['class'] == 1){
			                                $now = -$v['money'];
			                            }else{
			                                $now = $v['money'];
			                            }
			                            $money = $money + $now;
			                        }
			                    }
			                    //钱包收支明细表 添加 返现数据
			                    $money = $money + 30;
			                    model('wallet')->save(['user_id'=>$pasmen['id'],'status'=>1,'class'=>2,'money'=>30,'balance'=>$money]);
			                }
			            }
			            //查询所有产品代理商升级的条件
			            $identitygong = model('identitygong')->select()->toArray();
			
			            //判断自身是否提升等级
			            //查询资产表，汇总购买清单
			            $assets = model('assets')->where('user_id','=',$post['user_id'])->select()->toArray();
			            $money = 0;
			            foreach ($assets as $v){
			                if($v['class'] == 3){
			                    $money = $money + $v['money'];
			                }
			            }
			            $nowtime = 99;
			            if ($money >= 1000 && $money < 3000 && $user['ptsf'] == 10){
			                //变为普通会员
			                model('user')->save(['ptsf'=>1],['id'=>$post['user_id']]);
			                $nowtime = 1;
			            }elseif($money >= 3000 && $money < 6000 && $user['ptsf'] == 10 || $user['ptsf'] == 1){
			                //变为VIP会员
			                model('user')->save(['ptsf'=>2],['id'=>$post['user_id']]);
			                $nowtime = 2;
			            }elseif($money >= 6000 && $user['ptsf'] == 10 || $user['ptsf'] == 1 || $user['ptsf'] == 2){
			                //变为普通代理商
			                model('user')->save(['ptsf'=>3],['id'=>$post['user_id']]);
			                $nowtime = 3;
			            }
			            //当前用户查询直属和自身的下级资产表，汇总购买清单
			            //当前用户拥有的直属下级
			            $nowalluser = model('user')->where('parent_id','=',$user['id'])->select()->toArray();
			            $nowalluserid = '';
			            foreach ($nowalluser as $v){
			                $nowalluserid = $nowalluserid . $v['id'] . ',';
			            }
			            $nowalluserid = $nowalluserid . $user['id'];
			            //当前用户查询直属和自身的下级资产表，汇总购买清单
			            $nowassetsall = model('assets')->where('user_id','in',$nowalluserid)->select()->toArray();
			            $money = 0;
			            foreach ($nowassetsall as $v){
			                if($v['class'] == 3){
			                    $money = $money + $v['money'];
			                }
			            }
			            if($money >= $identitygong[0]['performance'] && $money < $identitygong[1]['performance']){
			                //当前用户升级产品区代理商
			                if($user['canpinsf'] == 99){
			                    model('user')->save(['canpinsf'=>4],['id'=>$user['id']]);
			                    $nowtime = 4;
			                }
			            }elseif($money >= $identitygong[1]['performance'] && $money < $identitygong[2]['performance']){
			                //当前用户升级产品市代理商
			                if($user['canpinsf'] == 99 || $user['canpinsf'] == 4){
			                    //当前用户直属下级有两个产品区代理
			                    $qnum = model('user')->where([
			                        ['parent_id','=',$user['id']],
			                        ['canpinsf','=',4]
			                    ])->select();
			                    if($qnum)
			                    {
			                        $qnum = count($qnum->toArray());
			                        if($qnum >= 2){
			                            model('user')->save(['canpinsf'=>5],['id'=>$user['id']]);
			                            $nowtime = 5;
			                        }
			                    }
			                }
			            }elseif($money >= $identitygong[2]['performance'] && $money < $identitygong[3]['performance']){
			                //当前用户升级产品省代理商
			                if($user['canpinsf'] == 99 || $user['canpinsf'] == 4 || $user['canpinsf'] == 5){
			                    //当前用户直属下级有三个产品市代理
			                    $qnum = model('user')->where([
			                        ['parent_id','=',$user['id']],
			                        ['canpinsf','=',5]
			                    ])->select();
			                    if($qnum)
			                    {
			                        $qnum = count($qnum->toArray());
			                        if($qnum >= 3){
			                            model('user')->save(['canpinsf'=>7],['id'=>$user['id']]);
			                            $nowtime = 6;
			                        }
			                    }
			                }
			            }
			            //直属上级身份升级，达到产品代理等级或普通代理商等级后汇总下级的消费总额和自身的消费总额，判断是否升级身份
			            if($pasmen){
			                if($pasmen['canpinsf'] !== 99 || $pasmen['ptsf'] == 3){
			                    //直属上级拥有的直属下级
			                    $alluser = model('user')->where('parent_id','=',$pasmen['id'])->select()->toArray();
			                    $alluserid = '';
			                    foreach ($alluser as $v){
			                        $alluserid = $alluserid . $v['id'] . ',';
			                    }
			                    $alluserid = $alluserid . $pasmen['id'];
			                    //上级查询直属和自身的下级资产表，汇总购买清单
			                    $assetsall = model('assets')->where('user_id','in',$alluserid)->select()->toArray();
			                    $money = 0;
			                    foreach ($assetsall as $v){
			                        if($v['class'] == 3){
			                            $money = $money + $v['money'];
			                        }
			                    }
			
			                    if($money >= $identitygong[0]['performance'] && $money < $identitygong[1]['performance']){
			                        //升级产品区代理商
			                        if($pasmen['canpinsf'] == 99){
			                            model('user')->save(['canpinsf'=>4],['id'=>$pasmen['id']]);
			                        }
			                    }elseif($money >= $identitygong[1]['performance'] && $money < $identitygong[2]['performance']){
			                        //升级产品市代理商
			                        if($pasmen['canpinsf'] == 99 || $pasmen['canpinsf'] == 4){
			                            //直属下级有两个产品区代理
			                            $qnum = model('user')->where([
			                                ['parent_id','=',$pasmen['id']],
			                                ['canpinsf','=',4]
			                            ])->select();
			                            if($qnum)
			                            {
			                                $qnum = count($qnum->toArray());
			                                if($qnum >= 2){
			                                    model('user')->save(['canpinsf'=>5],['id'=>$pasmen['id']]);
			                                }
			                            }
			                        }
			                    }elseif($money >= $identitygong[2]['performance'] && $money < $identitygong[3]['performance']){
			                        //升级产品省代理商
			                        if($pasmen['canpinsf'] == 99 || $pasmen['canpinsf'] == 4 || $pasmen['canpinsf'] == 5){
			                            //直属下级有三个产品市代理
			                            $qnum = model('user')->where([
			                                ['parent_id','=',$pasmen['id']],
			                                ['canpinsf','=',5]
			                            ])->select();
			                            if($qnum)
			                            {
			                                $qnum = count($qnum->toArray());
			                                if($qnum >= 3){
			                                    model('user')->save(['canpinsf'=>7],['id'=>$pasmen['id']]);
			                                }
			                            }
			                        }
			                    }
			                }
			            }
			
			            //积分
			            //当前用户自身消费获取积分
			            //购物后获取对应身份的积分
			            $order = model('order')->where('id','=',$post['id'])->find()->toArray();
			            $user = model('user')->where('id','=',$user['id'])->find()->toArray();
			            if($user['ptsf'] == 2){
			                $parent = model('user')->where([
			                    ['parent_id','=',$user['id']],
			                    ['ptsf','=',2]
			                ])->select();
			                if($parent){
			                    $parent = count($parent->toArray());
			                    if($parent = 1){
			                        $jf = round($order['money']*0.002,2);
			                        model('integral')->save(['user_id'=>$user['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$user['id'],$integralid);
			                        $addjf = $jf;
			                    }elseif($parent > 1){
			                        $jf = round($order['money']*0.004,2);
			                        model('integral')->save(['user_id'=>$user['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$user['id'],$integralid);
			                        $addjf = $jf;
			                    }
			                }
			            }elseif ($user['ptsf'] == 3 && $user['canpinsf'] == 99){
			                //当前用户为普通代理商
			                $parent = model('user')->where([
			                    ['parent_id','=',$user['id']],
			                    ['ptsf','in','10,1']
			                ])->select();
			                if($parent){
			                    $parent = count($parent->toArray());
			                    if($parent == 1){
			                        $jf = round($order['money']*0.002,2);
			                        model('integral')->save(['user_id'=>$user['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$user['id'],$integralid);
			                    }elseif($parent > 1){
			                        $jf = round($order['money']*0.004,2);
			                        model('integral')->save(['user_id'=>$user['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$user['id'],$integralid);
			                    }
			                }
			            }
			            //直属上级获取积分
			            if($pasmen){
			                if($pasmen['ptsf'] == 3 && $pasmen['canpinsf'] == 99){
			                    //直属上级只是普通代理商
			                    if($user['relation'] == 1){
			                        //上级和当前用户不是平级关系，还在关联中
			                        $jf = round($order['money']*$identitygong[0]['direct']*0.01,2);
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                    }elseif($user['relation'] == 4){
			                        //上级和当前用户达成过平级关系，已经取消关联，但有平级奖励
			                        $jf = round($order['money']*$identitygong[0]['direct']*0.0001,2);
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>4,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                    }
			                }elseif($pasmen['canpinsf'] == 4){
			                    //直属上级为区代理商
			                    if($user['relation'] == 1){
			                        //上级和当前用户不是平级关系，还在关联中
			                        //直推积分返佣
			                        $jf = round($order['money']*$identitygong[1]['direct']*0.01,2);
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                        //额外代理积分返佣
			                        $jf = round($order['money']*$identitygong[1]['division']*0.01,2);
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                    }elseif($user['relation'] == 4){
			                        //上级和当前用户达成过平级关系，已经取消关联，但有平级奖励
			                        //直推积分返佣
			                        $jf = round($order['money']*$identitygong[1]['direct']*0.0001,2);
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>4,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                    }
			
			                }elseif($pasmen['canpinsf'] == 5){
			                    if($user['relation'] == 1){
			                        //上级和当前用户不是平级关系，还在关联中
			                        //直属上级为市代理商
			                        //直推积分返佣
			                        $jf = round($order['money']*$identitygong[2]['direct']*0.01,2);
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                        //额外代理积分返佣
			                        $jf = round($order['money']*$identitygong[2]['division']*0.01,2);
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                        
			                    }elseif($user['relation'] == 4){
			                        //上级和当前用户达成过平级关系，已经取消关联，但有平级奖励
			                        $jf = round($order['money']*$identitygong[2]['direct']*0.0001,2);
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                    }
			                }elseif($pasmen['canpinsf'] == 7){
			                    if($user['relation'] == 1){
			                        //上级和当前用户不是平级关系，还在关联中
			                        //直属上级为省代理商
			                        //直推积分返佣
			                        $jf = round($order['money']*$identitygong[3]['direct']*0.01,2);
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                        //额外代理积分返佣
			                        $jf = round($order['money']*$identitygong[3]['division']*0.01,2);
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                    }elseif($user['relation'] == 4){
			                        //上级和当前用户达成过平级关系，已经取消关联，但有平级奖励
			                        $jf = round($order['money']*$identitygong[3]['direct']*0.0001,2);
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$jf,'source'=>1,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                    }
			                }
			            }
			
			            //市场互助积分
			            //身份满足普通代理商
			            if($user['ptsf'] == 3){
			                //上级拥有直属下级为普通代理商以上的数量
			                if($pasmen){
			                	$pasnum = model('user')->where([
			                        ['parent_id','=',$pasmen['id']],
			                        ['ptsf','=',3]
			                	])->select();
			                }else{
			                	$pasnum = false;
			                }
			                if($pasnum){
			                    //上级的互助积分
			                    $pasnum = count($pasnum->toArray());
			                    if($pasnum == 2 && isset($addjf)){
			                        $dqjf = $addjf*0.07;
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$dqjf,'source'=>5,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);
			                        
			                    }elseif($pasnum >= 3 && isset($addjf)){
			                        $dqjf = $addjf*0.14;
			                        model('integral')->save(['user_id'=>$pasmen['id'],'money'=>$order['money'],'order_id'=>$post['id'],'num'=>$dqjf,'source'=>5,'status'=>1]);
			                        $integralid = model('integral')->id;
			                        jfmx($jf,$pasmen['id'],$integralid);//上上级的互助积分
			                        
			                    }
			                }
			            }
			            //relation 1关联中，2取消关联，3无关联，4平级奖励
			            //平级奖励
			            $user = model('user')->where('id','=',$user['id'])->find()->toArray();
			            if($user['ptsf'] == 3){
			                //直属上级数据
			                $pasmen = model('user')->where([
			                    ['id','=',$user['parent_id']],
			                    ['ptsf','=',3]
			                ])->find();
			                if($pasmen){
			                    $pasmen = $pasmen->toArray();
			                    //上级和当期用户的身份等级相同
			                    //取消他们之间的关联
			                    if($user['canpinsf'] == $pasmen['canpinsf'] && $user['relation'] == 1){
			                        model('user')->save(['relation'=>2],['id'=>$user['id']]);
			                        $pageshu = model('user')->where([
			                            ['parent_id','=',$pasmen['id']],
			                            ['ptsf','=',3],
			                            ['relation','=',2]
			                        ])->select()->toArray();
			                        //业绩清零
			                        $yj = model('assets')->field('id,relation')->where('user_id','=',$user['id'])->select()->toArray();
			                        foreach ($yj as $k=>$v){
			                            $yj[$k]['relation'] = 2;
			                        }
			                        model('assets')->saveAll($yj);
			                        //重新统计上级业绩
			                        //查询还没脱离关系的下级
			                        $pasall = model('user')->field('id')->where([
			                            ['parent_id','=',$pasmen['id']],
			                            ['relation','=',1]
			                        ])->select();
			                        if($pasall){
			                            $pasall = $pasall->toArray();
			                            $idall = implode(',',$pasall);
			                            //查询还在关联中的用户的购买记录
			                            $yj = model('assets')->field('money,moneyclass')->where([
			                                ['user_id','in',$idall],
			                                ['class','=',3]
			                            ])->select()->toArray();
			                            $money = 0;
			                            foreach ($yj as $v){
			                                $money = $money + $v['money'];
			                            }
			                            //合计购买金额，刷新业绩
			                            $money = round($money,2);
			                            model('user')->save(['achievement'=>$money],['id'=>$pasmen['id']]);
			                        }
			                        $pageshuz = count($pageshu);
			                        if($pageshuz >= 6){
			                            //当前用户的上级拥有6个及以上平级的直属用户
			                            //达成了平级奖励条件
			                            //每次可以获得新增积分的1%
			                            foreach ($pageshu as $k=>$v){
			                                $pageshu[$k]['relation'] = 4;
			                            }
			                            model('user')->save($pageshu);
			                        }
			                    }
			                }
			            }
			            //事务提交前再检测一次是否超出库存
			            $order = model('order')->where('id','=',$post['id'])->with('product')->find()->toArray();
			            //库存减少
			            //库存
			            if($order['product']['stock'] < 0){
			                Db::rollback();
			                return fh(404,'error','库存不足，购买失败',[]);
			            }else{
			                Db::commit();
			            }
			        }catch (\Exception $e){
			            return fh(500,'error','f3'.$e->getMessage(),[]);
			        }  
                }
            }
        }
        echo $payModel->notifyResult();
    }
}
